<template>
  <!-- 设备管理 -->
  <div id="equipmentInfoManageDiv">
    <Breadcrumb content="设备台账" />
    <div class="bodyContent">
      <vxe-toolbar perfect>
        <template #buttons>
          <vxe-form :data="dataform">
            <vxe-form-item title="快速查询:" field="searchValue">
              <template #default="{ data }">
                <vxe-input style="width: 180px" v-model="data.searchValue" type="search" clearable class="vxeInputSearch" placeholder="设备名称、编码、规格型号" @keyup="findEquipmentInfoManageList" @search-click="findEquipmentInfoManageList()"></vxe-input>
              </template>
            </vxe-form-item>
            <vxe-form-item>
              <!--              <vxe-button type="text" status="success" icon="vxe-icon-search" content="查询" @click="findEquipmentInfoManageList"></vxe-button>-->
              <vxe-button type="text" icon="vxe-icon-add" class="button-blue" content="新建" @click="handleAdd"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="handleDelete"></vxe-button>
              <vxe-button type="text" class="button-blue margin-right-sm" icon="vxe-icon-print" @click="printTable">打印</vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-file-excel" content="导出表格" @click="exportExcelReport('#printTest', '设备台账')"></vxe-button>
              <vxe-button type="text" class="button-blue margin-right-sm" icon="vxe-icon--refresh" @click="synInterData">同步仪器</vxe-button>
            </vxe-form-item>
          </vxe-form>
        </template>
      </vxe-toolbar>
      <div class="equipmentInfoManageTableDiv">
        <Splitpanes>
          <Pane size="50">
            <!-- <div class="equipmentInfoManageTableDiv"> -->
            <vxe-table ref="equipmentInfoManageTable" class="mytable-scrollbar" :loading="loading" border height="auto" :data="equipmentInfoManageList" :row-config="{ isHover: true, isCurrent: true }" :column-config="{ resizable: true }" show-overflow @current-change="curRowChangeEvent">
              <vxe-column type="checkbox" width="26"></vxe-column>
              <vxe-column type="seq" title="序号" width="50"></vxe-column>
              <vxe-column field="image" title="图片" width="90" align="center" class-name="col-img">
                <template #default="{ row }">
                  <div style="width: 70px; height: calc(100% - 2px); margin: 1px auto" v-if="row.imgUrl">
                    <el-image style="height: 100%" :src="row.imgUrl" fit="contain">
                      <div slot="error" class="image-slot">
                        <i class="iconfont icon-weixiubeijing bg-gray"></i>
                      </div>
                    </el-image>
                  </div>
                  <span v-else class="error-image iconfont icon-weixiubeijing bg-gray"></span>
                </template>
              </vxe-column>
              <vxe-column field="equiptCode" title="编码" width="120"></vxe-column>
              <vxe-column field="equiptName" title="名称" width="160"></vxe-column>
              <vxe-column field="equiptTypeName" title="设备类型" width="90"></vxe-column>
              <vxe-column field="status" title="设备状态" width="90" align="center">
                <template #default="{ row }">
                  <span v-if="row.status" class="table-tag" :class="`bg-${enums.emInsStates[Number(row.status) - 1].color}`">{{ enums.emInsStates[Number(row.status) - 1].label }}</span>
                </template>
              </vxe-column>
              <vxe-column field="usingStatus" title="使用状态" width="90" align="center">
                <template #default="{ row }">
                  <span v-if="row.usingStatus" class="table-tag" :class="`bg-${enums.emUsingStatus[Number(row.usingStatus)].color}`">{{ enums.emUsingStatus[Number(row.usingStatus)].label }}</span>
                </template>
              </vxe-column>
              <vxe-column field="specification" title="型号" width="120"></vxe-column>
              <vxe-column field="managerName" title="负责人" width="100">
                <template #default="{ row }">
                  {{ (row.managerName && row.managerName.realname) || '' }}
                </template>
              </vxe-column>
              <vxe-column field="manuName" title="生产商" width="160"></vxe-column>
              <vxe-column field="produceDate" title="生产日期" width="120"></vxe-column>
              <vxe-column field="activationDate" title="启用日期" width="120"></vxe-column>
              <vxe-column field="warrantyPeriod" title="保修期限" width="100"></vxe-column>
              <vxe-column field="creatorName" title="建档人" width="100">
                <template #default="{ row }">
                  {{ (row.creatorName && row.creatorName.realname) || '' }}
                </template>
              </vxe-column>
              <vxe-column field="createTime" title="建档时间" width="120"></vxe-column>
              <vxe-column field="remark" title="备注" min-width="100"></vxe-column>
            </vxe-table>
            <!-- </div> -->
          </Pane>
          <Pane size="50">
            <el-tabs type="border-card" v-model="activeTab">
              <el-tab-pane label="基本信息" name="0">
                <el-container>
                  <el-scrollbar style="height: 100%; padding-right: 10px; width: calc(100% - 10px)">
                    <div class="padding-sm" style="width: 100%; padding-top: 0">
                      <vxe-toolbar perfect>
                        <template #tools>
                          <vxe-button icon="vxe-icon-save" type="text" class="text-cyan" content="保存" @click="submitUpload"></vxe-button>
                        </template>
                      </vxe-toolbar>

                      <el-descriptions :column="3" :labelStyle="{ width: '110px', background: '#fff', color: '#000', textAlign: 'center' }" :contentStyle="{ width: '130px' }" border style="margin-right: 15px">
                        <el-descriptions-item label="设备编码号">
                          <vxe-input disabled v-model="form.equiptCode"></vxe-input>
                        </el-descriptions-item>
                        <el-descriptions-item label="设备名称" :span="1">
                          <el-form :model="form" ref="formRef" :rules="formRules">
                            <el-form-item prop="equiptName">
                              <el-input v-model="form.equiptName" style="width: 180px" />
                            </el-form-item>
                          </el-form>
                        </el-descriptions-item>
                        <el-descriptions-item label="" :span="1">
                          <div id="qrcode" style="margin: auto"></div>
                        </el-descriptions-item>

                        <el-descriptions-item label="设备型号">
                          <el-form :model="form" ref="formRef" :rules="formRules">
                            <el-form-item prop="specification">
                              <el-input v-model="form.specification" style="width: 180px" />
                            </el-form-item>
                          </el-form>
                        </el-descriptions-item>

                        <el-descriptions-item label="设备类型">
                          <el-form :model="form" ref="formRef" :rules="formRules">
                            <el-form-item prop="equiptTypeCode">
                              <el-select clearable v-model="form.equiptTypeCode" placeholder="请选择" ref="selectOrgRef" filterable style="width: 180px">
                                <el-option hidden :value="form.equiptTypeCode ? form.equiptTypeCode : ''" :label="form.equiptTypeName"></el-option>
                                <el-tree :data="equiptTypeList" :props="defaultProps" @node-click="handleOrgNodeClick" highlight-current node-key="id" class="tools-tree"></el-tree>
                              </el-select>
                            </el-form-item>
                          </el-form>
                        </el-descriptions-item>

                        <el-descriptions-item label="生产商" :span="2">
                          <vxe-input v-model="form.manuName"></vxe-input>
                        </el-descriptions-item>
                        <el-descriptions-item label="建档人">
                          <template>
                            <VxePulldownSelection
                              :url="'/api/user/getUserInfoList'"
                              @confirmClick="dropPullDownConfirm"
                              :tableColumn="[
                                { field: 'username', title: '编号', width: '60px' },
                                { field: 'realname', title: '姓名' }
                              ]"
                              :aimKeys="[{ aimKey: 'chkDoctor', rowKey: 'username' }]"
                              :displayTexts="['realname']"
                              :displayTextObj="form.chkDoctor ? form.chkDoctor : ''"
                            />
                          </template>
                        </el-descriptions-item>
                        <el-descriptions-item label="建档日期">
                          <vxe-input v-model="form.createTime" type="date" transfer></vxe-input>
                        </el-descriptions-item>
                        <el-descriptions-item label="生产日期">
                          <vxe-input v-model="form.produceDate" type="date" transfer></vxe-input>
                        </el-descriptions-item>
                        <el-descriptions-item label="出厂日期">
                          <vxe-input v-model="form.factoryDate" type="date" transfer></vxe-input>
                        </el-descriptions-item>
                        <el-descriptions-item label="采购日期">
                          <vxe-input v-model="form.purchaseDate" type="date" transfer></vxe-input>
                        </el-descriptions-item>

                        <el-descriptions-item label="启用日期">
                          <vxe-input v-model="form.activationDate" type="date" transfer></vxe-input>
                        </el-descriptions-item>

                        <el-descriptions-item label="保修期限">
                          <vxe-input v-model="form.warrantyPeriod" type="date" transfer clearable></vxe-input>
                        </el-descriptions-item>
                        <el-descriptions-item label="采购人">
                          <VxePulldownSelection
                            :url="'/api/user/getUserInfoList'"
                            @confirmClick="dropPullDownConfirm"
                            :tableColumn="[
                              { field: 'username', title: '编号', width: '60px' },
                              { field: 'realname', title: '姓名' }
                            ]"
                            :aimKeys="[{ aimKey: 'purchaser', rowKey: 'username' }]"
                            :displayTexts="['realname']"
                            :displayTextObj="form.purchaser ? form.purchaser : ''"
                          />
                        </el-descriptions-item>
                        <el-descriptions-item label="采购金额">
                          <vxe-input v-model="form.amount"></vxe-input>
                        </el-descriptions-item>

                        <el-descriptions-item :span="3" label="设备负责人">
                          <VxePulldownSelection
                            :url="'/api/user/getUserInfoList'"
                            @confirmClick="dropPullDownConfirm"
                            :tableColumn="[
                              { field: 'username', title: '编号', width: '60px' },
                              { field: 'realname', title: '姓名' }
                            ]"
                            :aimKeys="[{ aimKey: 'manager', rowKey: 'username' }]"
                            :displayTexts="['realname']"
                            :displayTextObj="form.manager ? form.manager : ''"
                          />
                        </el-descriptions-item>
                        <el-descriptions-item :span="3" label="售后负责人">
                          <vxe-input v-model="form.productLeader" clearable></vxe-input>
                        </el-descriptions-item>
                        <el-descriptions-item :span="3" label="售后负责人电话">
                          <el-form ref="prodLeaderPhoneRef" :model="form" :inline="true">
                            <el-form-item prop="prodLeaderPhone">
                              <el-input style="width: 180px" v-model="form.prodLeaderPhone" clearable></el-input>
                            </el-form-item>
                          </el-form>
                        </el-descriptions-item>
                        <el-descriptions-item label="设备状态">
                          <el-form :model="form" ref="formRef" :rules="formRules">
                            <el-form-item prop="status">
                              <el-select v-model="form.status" clearable placeholder="Select" style="width: 180px">
                                <el-option v-for="(item, index) in enums.emInsStates" :key="index" :value="`${item.value}`" :label="item.label" />
                              </el-select>
                            </el-form-item>
                          </el-form>
                        </el-descriptions-item>
                        <el-descriptions-item label="使用状态">
                          <el-form :model="form" ref="formRef" :rules="formRules">
                            <el-form-item prop="usingStatus">
                              <el-select v-model="form.usingStatus" clearable placeholder="请选择使用状态" style="width: 180px">
                                <el-option v-for="(item, index) in enums.emUsingStatus" :key="index" :value="`${item.value}`" :label="item.label" />
                              </el-select>
                            </el-form-item>
                          </el-form>
                        </el-descriptions-item>

                        <el-descriptions-item :span="3" label="所属科室">
                          <el-form :model="form" ref="formRef">
                            <el-form-item prop="deptCodeNa">
                              <VxePulldownSelection
                                :url="'/api/sys/findDepartmentListbyCurrentUserOrg'"
                                @confirmClick="dropPullDownConfirm"
                                :tableColumn="[
                                  { field: 'code', title: '编码', width: '60px' },
                                  { field: 'name', title: '名称' }
                                ]"
                                :aimKeys="[
                                  { aimKey: 'deptCode', rowKey: 'code' },
                                  { aimKey: 'deptCodeNa', rowKey: 'name' }
                                ]"
                                :displayTexts="['name']"
                                :displayTextObj="form.deptCode ? form.deptCode : ''"
                              />
                            </el-form-item>
                          </el-form>
                        </el-descriptions-item>
                        <el-descriptions-item :span="3" label="备注">
                          <vxe-textarea v-model="form.remark"></vxe-textarea>
                        </el-descriptions-item>
                      </el-descriptions>

                      <vxe-toolbar perfect class="margin-top">
                        <template #buttons>
                          <span class="text-blue text-bold margin-left-sm">设备图片</span>
                        </template>
                      </vxe-toolbar>
                      <div style="width: clac(100% - 20px); border: 1px #eee solid">
                        <el-upload class="upload-demo" ref="fileUpload" :action="uploadUrl" :data="uploadData" :headers="headers" multiple :limit="10" list-type="picture-card" :auto-upload="false" v-model:file-list="fileList" :on-preview="handlePictureCardPreview" :on-change="fileSelectChange" :before-upload="onbeforeUpload" :on-success="onSucessUpload" :before-remove="fileRemove">
                          <el-icon>
                            <Plus />
                          </el-icon>
                        </el-upload>
                      </div>

                      <vxe-toolbar perfect class="margin-top">
                        <template #buttons>
                          <span class="text-blue text-bold margin-left-sm">相关文档</span>
                        </template>
                      </vxe-toolbar>
                      <Documents v-show="documentsShow" ref="documentsRef" />
                    </div>
                  </el-scrollbar>
                </el-container>
              </el-tab-pane>
              <el-tab-pane label="维修" name="1" :disabled="!form.id">
                <RepairOrderList ref="repairOrderListRef"></RepairOrderList>
              </el-tab-pane>
              <el-tab-pane label="保养" name="2" :disabled="!form.id">
                <MaintainOrdeList ref="maintainOrdeListRef"></MaintainOrdeList>
              </el-tab-pane>
              <el-tab-pane label="巡检记录" name="3" :disabled="!form.id">
                <PatrolTask ref="patrolTaskRef"></PatrolTask>
              </el-tab-pane>
              <el-tab-pane label="点检记录" name="4" :disabled="!form.id">
                <SpotcheckTask ref="spotcheckTaskRef"></SpotcheckTask>
              </el-tab-pane>
              <el-tab-pane label="时间节点" name="5" :disabled="!form.id">
                <TimelineComp ref="timelineCompRef"></TimelineComp>
              </el-tab-pane>
            </el-tabs>
          </Pane>
        </Splitpanes>
      </div>
      <!-- <el-drawer v-model="modalShow" title="新建" :direction="rtl" size="calc(100% - 70px)" :before-close="handleClose">
        <template #default>

        </template>
      </el-drawer> -->
      <!-- 大图预览 -->
      <el-dialog v-model="dialogVisibleImg">
        <img :src="dialogImageUrl" alt="" />
      </el-dialog>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus';
import { Splitpanes, Pane } from 'splitpanes';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { IsEmpty, formatDateTime, autoIncrementNumber, notifyMessage, notifyType } from '@/utils/common';
import VxePulldownSelection from '@/components/VxePulldownSelection.vue';
import Template from '@/views/lab_sys/lab_bus/components/Template.vue';
import { enums } from '@/enums/enumerator.js';
import Documents from '@/components/Documents.vue';
import PatrolTask from '@/components/PatrolTask.vue';
import RepairOrderList from '../lab_sys/eq_set/RepairOrderList.vue';
import MaintainOrdeList from '../lab_sys/eq_set/MaintainOrdeList.vue';
import SpotcheckTask from '@/components/SpotcheckTask.vue';
import TimelineComp from '@/components/TimelineComp.vue';

import QRCode from 'qrcodejs2-fix';
import { log } from 'console';

let documentsRef: any = ref(null); //文档ref
let patrolTaskRef: any = ref(null); //文档ref
let spotcheckTaskRef: any = ref(null); //文档ref
let repairOrderListRef: any = ref(null);
let maintainOrdeListRef: any = ref(null);
let timelineCompRef: any = ref(null); //文档ref
let headers = {
  Authorization: 'Bearer ' + localStorage.getItem('token')
};
// 定义全局变量区====================================
let { proxy }: any = getCurrentInstance();
const pageSizeList = [10, 50, 100, 200, 500];
let contHeight = ref(0); // 获取屏幕高度
let conWidth = document.documentElement.clientWidth; // 获取屏幕宽度

// 查询表单数据
let dataform = {
  equiptType: '',
  searchValue: ''
};
let searchForm = {
  childSearchValue: ''
};

// 表单规则
let formRules = reactive({
  equiptName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
  specification: [{ required: true, message: '请输入设备型号', trigger: 'blur' }],
  equiptTypeCode: [
    {
      required: true,
      message: '请选择设备类型',
      trigger: 'change'
    }
  ],
  status: [
    {
      required: true,
      message: '请选择设备状态',
      trigger: 'change'
    }
  ],
  usingStatus: [
    {
      required: true,
      message: '请选择使用状态',
      trigger: 'change'
    }
  ],
  deptCodeNa: [{ required: true, message: '请选择所属科室' }]
});

// 表格数据
let equipmentInfoManageList: any = reactive([]);
let loading = ref(false);

let uploadUrl = (window as any).apiUrl.VITE_SERVER_URL + '/api/eq/eqEquipmentImage/uploadEqEquipmentImage';
let uploadData = reactive({
  equiptId: null
});

// 抽屉 Tabs
let activeName = ref('0');
let activeTab = ref('0');
let modalShow = ref(false); //新建抽屉
let equiptTypeList: any = reactive([]); //设备类型列表数据
let equiptTypeThreeList: any = reactive([]); //设备类型列表数据
let defaultProps = {
  children: 'children',
  label: 'name'
};
//let employee = proxy.$store.state.userInfo.employee;
let employee = ref({});
let url = ref('');
let dialogVisibleImg = ref(false); //图片查看
let dialogImageUrl = ref(''); //放大图片地址

// 基本信息 表单
let form = reactive({
  id: null,
  equiptCode: '',
  equiptName: '',
  inputCode: '',
  displayOrder: '',
  specification: '', //设备型号
  equipmentBarcode: '', //设备条码
  manuName: '', //生产商
  warrantyPeriod: '', //保修期限
  produceDate: null, //生产日期
  factoryDate: null, //出厂日期
  purchaseDate: null, //采购日期
  activationDate: null, //启用日期
  createTime: formatDateTime(new Date(), 'yyyy-MM-dd'), //建档日期
  purchaserId: null, //采购人
  purchaser: '',
  creator: '',
  managerId: null, //设备负责人
  manager: '',
  productLeader: '', //售后负责人
  prodLeaderPhone: '', //售后负责人电话
  remark: '', //备注
  poct: 1, //备注
  status: '', //0:正常；1：故障；2：带病运行
  usingStatus: '', //使用状态
  deptCode: '',
  insLevel: '', //设备等级
  eqEquipmentImages: [
    {
      id: '',
      imagePath: ''
    }
  ], //设备图片
  searchValue: '',
  equiptTypeCode: '',
  equiptTypeName: '',
  amount: ''
});

//文件类型
let fileType = ref('');

// #region 【基本信息】
let selectEquipmentInfoModal = ref(false);
let documentsShow = ref(false);
let saveName = ref('');
let equipmentInfoList: any = reactive([]);

// // 点击的设备id
let curSelRowObj = ref({});
// #region【子设备】
let checkedIds: any = reactive([]);

let fileList: any = reactive([]);

let uploadArrFile: any = reactive([]);
let uploadArrDoc: any = reactive([]);
/**文件上傳組件對象*/
const fileUpload = ref(null);
// 方法定义区 ================================
/** 页面加载时 **/
onMounted(() => {
  contHeight.value = document.documentElement.clientHeight;
  url.value = proxy.$router.currentRoute.path;
  const today = new Date();
  findEquiptTypeList();
  findEquipmentInfoManageList();
});

//获取设备类型(树形结构数据集合)
function findEquiptTypeList() {
  const url = '/api/eq/eqEquiptType/findEquiptTypeTreeList';
  equiptTypeList.length = 0; //放入数据前清空数据
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { searchValue: '' } })
    .then((res: any) => {
      equiptTypeList.push(...res.data);
    })
    .catch((err: any) => {
      // VxeMessage('获取机构列表失败',VxeNotifyType.error)
    });
}

// 设备类型 点击当前行
function handleOrgNodeClick(data: any) {
  form.equiptTypeCode = data.code;
  form.equiptTypeName = data.name;
  const selectOrgRef: any = proxy.$refs['selectOrgRef'];
  selectOrgRef.blur();
}

// 获取表格数据+查询
async function findEquipmentInfoManageList() {
  equipmentInfoManageList.length = 0;
  loading.value = true;
  const url = '/api/eq/eqEquipment/findEqEquipmentPageList';
  const data = {
    poct: 1,
    searchValue: IsEmpty(dataform.searchValue) ? '' : form.searchValue.trim(),
    sorting: ''
  };
  proxy.$http
    .get(url, { params: data })
    .then(async (res: any) => {
      await res.data.forEach((item) => {
        if (item.eqEquipmentImages) {
          item.imgUrl = item.eqEquipmentImages.length > 0 ? (window as any).apiUrl.VITE_SERVER_URL + item.eqEquipmentImages[0].imagePath : '';
        }
      });
      equipmentInfoManageList = res.data;

      proxy.$nextTick(() => {
        curRowChangeEvent({ row: equipmentInfoManageList[0] });
      });
      loading.value = false;
    })
    .catch((err) => {
      loading.value = false;
    });
}

// 清空表单
function clearForm() {
  form.id = null;
  form.equiptCode = '';
  form.equiptName = '';
  form.inputCode = '';
  form.displayOrder = '';
  form.specification = ''; //设备型号
  form.equipmentBarcode = ''; //设备条码
  form.manuName = ''; //生产商
  form.warrantyPeriod = ''; //保修期限
  form.produceDate = null; //生产日期
  form.factoryDate = null; //出厂日期
  form.purchaseDate = null; //采购日期
  form.activationDate = null; //启用日期
  form.createTime = formatDateTime(new Date(), 'yyyy-MM-dd'); //建档日期
  form.purchaserId = null; //采购人
  form.purchaser = '';
  form.creator = '';
  form.managerId = null; //设备负责人
  form.manager = '';
  form.productLeader = ''; //售后负责人
  form.prodLeaderPhone = ''; //售后负责人电话
  form.remark = ''; //备注
  form.status = ''; //0=正常；1：故障；2：带病运行
  form.usingStatus = ''; //使用状态
  form.deptCode = ''; //科室
  form.insLevel = ''; //设备等级
  form.eqEquipmentImages = []; //设备图片
  form.searchValue = '';
  form.amount = '';
  form.poct = 1;
  (form.equiptTypeCode = ''), (form.equiptTypeName = '');
}

// 创建
function handleAdd() {
  clearForm();
  modalShow.value = true;
  documentsShow.value = false;
  fileList.length = 0;
}
//删除
function handleDelete() {
  const xTable = proxy.$refs.equipmentInfoManageTable as any;
  const selectRows = xTable.getCheckboxRecords();
  if (selectRows.length <= 0) {
    proxy.$XModal.message({ content: '请先选中要删除的项', status: 'warning' });
    return;
  }
  proxy.$XModal.confirm('您确定要删除吗？').then((type) => {
    if (type === 'confirm') {
      const url = '/api/eq/eqEquipment/batchDeleteEqEquipment';
      proxy.$http
        .post(url, selectRows)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('删除设备成功', VxeNotifyType.success);
            findEquipmentInfoManageList();
          } else {
            VxeMessage('删除设备失败', VxeNotifyType.error);
          }
        })
        .catch((err) => {
          proxy.$XModal.message({ content: '删除时出现异常', status: 'error' });
        });
    }
  });
}
//同步仪器数据
function synInterData() {
  const url = '/api/eq/eqEquipment/synInterData';
  proxy.$http
      .get(url)
      .then((res: any) => {
        if (res.status.code === 1) {
          VxeMessage('同步仪器结果成功', VxeNotifyType.success);
          findEquipmentInfoManageList();
        } else {
          VxeMessage('同步仪器结果失败', VxeNotifyType.error);
        }
      })
      .catch((err) => {
        proxy.$XModal.message({ content: '删除时出现异常', status: 'error' });
      });
}
//打印
let isPrinting = ref(false);
async function printTable() {
  isPrinting.value = true;
  const $table = proxy.$refs.equipmentInfoManageTable as any;
  $table.print();
  isPrinting.value = false;
}
function exportExcelReport(dom, title = '设备台账') {
  const $table = proxy.$refs.equipmentInfoManageTable as any;
  const selectRows = $table.getCheckboxRecords();
  if (selectRows.length <= 0) {
    proxy.$XModal.message({ content: '还未选择需要导出的数据', status: 'warning' });
    return;
  }
  $table.exportData({ data: $table.getCheckboxRecords(), type: 'csv', filename: title, useStyle: true });
}

// 表格点击当前行
function curRowChangeEvent({ row }) {
  fileList.length = 0;
  clearForm();
  // 默认选中第一行
  (proxy.$refs.equipmentInfoManageTable as any).setCurrentRow(row);
  documentsShow.value = true;
  documentsRef.value?.findFolderList(row.equiptCode);
  Object.assign(form, row);
  if (form.eqEquipmentImages) {
    form.eqEquipmentImages.forEach((item) => {
      fileList.push({
        id: item.id,
        url: (window as any).apiUrl.VITE_SERVER_URL + item.imagePath
      });
    });
    /*    proxy.$forceUpdate();*/
  }
  document.getElementById('qrcode').innerHTML = '';
  proxy.$nextTick(() => {
    new QRCode(document.getElementById('qrcode'), {
      text: getTwoCodeInfo(row),
      width: 75,
      height: 75,
      colorDark: '#000000',
      colorLight: '#ffffff'
    });
  });
  curSelRowObj = row;
  patrolTaskRef.value?.findMaintainDetailList(form.id);
  spotcheckTaskRef.value?.findMaintainDetailList(form.id);
  repairOrderListRef.value?.initPage(form.id);
  maintainOrdeListRef.value?.initPage(form.id);
  timelineCompRef.value?.getApprovalList(form);
}
const getTwoCodeInfo = (item: any) => {
  const obj = {
    equiptCode: item.equiptCode,
    equiptName: item.equiptName,
    equiptTypeName: item.equiptTypeName
  };
  return JSON.stringify(obj);
};

// 抽屉==============================================

// 下拉选中 抽屉里的组件
function dropPullDownConfirm(e) {
  e.aimKeys.forEach((m) => {
    form[m.aimKey] = e.row[m.rowKey];
  });
}

//关闭抽屉
function drawerClosed() {
  modalShow.value = false;
}

// 上传文件改变事件
function onbeforeUpload(file) {
  if (IsEmpty(form.id)) {
    return false;
  }
  uploadData.equiptId = form.id;
}

function onSucessUpload(respone, file, fileList) {
  console.log('respone', respone);
  if (respone && respone.status.code === 1) {
    file.id = respone.data.id;
    file.url = (window as any).apiUrl.VITE_SERVER_URL + respone.data.imagePath;
  }
}

// 上传文件改变事件
function fileSelectChange(file, fileList) {
  uploadArrFile.push(file.raw);
}

// 上传文档改变事件
function docSelectChange(file, fileList) {
  uploadArrDoc.push(file.raw);
}

// 删除上传文件
function fileRemove(file) {
  if (IsEmpty(file.id)) {
    const index = uploadArrFile.indexOf(file);
    if (index > -1) {
      uploadArrFile.splice(index, 1);
    }
  } else if (file.status === 'success') {
    const url = '/api/eq/eqEquipmentImage/deleteFileById';
    proxy.$http
      .get(url, { params: { id: file.id, filePath: file.url } })
      .then((res: any) => {
        const index = uploadArrFile.indexOf(file);
        if (index > -1) {
          uploadArrFile.splice(index, 1);
        }
        findEquipmentInfoManageList();
        VxeMessage('删除成功', VxeNotifyType.success);
      })
      .catch((err: any) => {
        loading.value = false;
        VxeMessage('删除失败', VxeNotifyType.error);
      });
  }
}
//手动上传文件 保存
async function submitUpload() {
  proxy.$refs.formRef.validate((vil: any) => {
    if (!vil) {
      return;
    } else {
      const data = form;
      if (IsEmpty(data.id)) {
        data.createTime += ' 00:00:00';
      }
      //判断新建和编辑
      const url = '/api/eq/eqEquipment/saveOrUpdateEqEquipment';
      proxy.$http
        .post(url, data)
        .then((res: any) => {
          Object.assign(form, res.data);
          let $form = proxy.$refs.fileUpload;
          $form.submit();
          setTimeout(() => {
            findEquipmentInfoManageList();
          }, 500);

          VxeMessage('保存成功', VxeNotifyType.success);
        })
        .catch((err: any) => {
          loading.value = false;
          VxeMessage('保存失败', VxeNotifyType.error);
        });
    }
  });
}
// 大图查看
function handlePictureCardPreview(file) {
  dialogImageUrl.value = file.url;
  dialogVisibleImg.value = true;
}

// 当前未用到===============================
function handleClick() {
  if (activeName.value === '0') {
    findEquipmentInfoManageList();
  } else if (activeName === '1') {
  }
}

// 弹框关闭
function hideEquipmentInfoModal() {
  clearForm();
  fileList.length = 0;
  uploadArrFile.length = 0;
  modalShow.value = false;
}

//Pulldown下拉选中事件
function pulldownSelectConfirm(e, row) {
  e.aimKeys.forEach((item) => {
    row[item.targetField] = e.row[item.sourceField];
  });
}

// 获取子设备
function getChildEquipmentInfo() {
  const url = '/api/ems/equipment-info';
  const data = {
    parentId: form.id,
    sorting: '',
    pageIndex: 0,
    pageSize: 200
  };
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      loading.value = false;
    })
    .catch((err) => {
      loading.value = false;
      proxy.$alert(err.data.error.message, '提示');
    });
}

// 获取设备列表
function getEquipmentInfo() {
  equipmentInfoList.length = 0;
  const url = '/api/ems/equipment-info';
  const data = {
    filter: IsEmpty(searchForm.childSearchValue) ? '' : searchForm.childSearchValue.trim(),
    sorting: '',
    pageIndex: 0,
    pageSize: 200
  };
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      equipmentInfoList.push(...res.items);
      proxy.$nextTick(() => {
        isCheckedEqInfo();
      });
      loading.value = false;
    })
    .catch((err) => {
      loading.value = false;
      proxy.$alert(err.data.error.message, '提示');
    });
}
function isCheckedEqInfo() {
  const checkedIds = checkedIds;
  const equipmentInfoList = equipmentInfoList;
  const checkedIndex = [];
  for (const item of checkedIds) {
    const index = equipmentInfoList.findIndex((row) => {
      return row.id === item;
    });
    if (index >= 0) {
      checkedIndex.push(index);
    }
  }
  //勾选对应的项目
  if (checkedIndex && checkedIndex.length > 0) {
    for (const key of checkedIndex) {
      (proxy.$refs.equipmentInfoTable as any).setCheckboxRow(equipmentInfoList[key], true);
    }
  }
}

function folderRowClick({ row }: any) {
  dataform.equiptType = row.id;
  (proxy.$refs.folderTable as any).setCurrentRow(row);
  findEquipmentInfoManageList();
}
function validateIsOpen(row) {
  return (proxy.$refs.folderTable as any).isTreeExpandByRow(row);
}
</script>
<style lang="scss" scoped>
#equipmentInfoManageDiv {
  width: 100%;
  height: 100%;

  .bodyContent {
    // 附加按钮间距
    .button-blue,
    .button-red {
      margin: 5px 0 5px 5px;
    }
    height: calc(100% - 60px);

    :deep(.vxe-form--item-inner) {
      margin-right: 16px;
    }

    .equipmentInfoManageTableDiv {
      background-color: $base-white;
      height: calc(100% - 36px);

      .vxe-table {
        .error-image,
        .image-slot > i {
          font-size: 24px;
          line-height: 40px;
          padding: 6px 10px;
        }

        .col-img {
          .vxe-cell {
            height: 40px;
            max-height: 100%;
          }
        }

        .table-tag {
          display: inline-block;
          width: 60px;
          text-align: center;
        }
      }
      :deep(.el-tabs) {
        height: 100%;
        .el-tabs__content {
          height: calc(100% - 40px);
          padding: 0;
          .el-tab-pane {
            height: 100%;
          }
        }
      }
    }
  }
  :deep(.vxe-body--column) {
    height: 50px;
    .vxe-cell {
      height: 100%;
    }
  }
}
</style>

<style lang="scss">
.el-drawer {
  .el-drawer__header {
    padding: 15px;
    margin-bottom: 0;
  }

  .el-tabs {
    height: 100%;

    .el-tabs__header {
      margin-bottom: 0;
    }

    .el-tabs__content {
      padding: 0;
      height: calc(100% - 40px);
    }

    .el-tab-pane {
      height: 100%;
    }
  }
}
</style>
